package com.charmpeach.tsss.crawler;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.baidu.pcs.BaiduPCSActionInfo;
import com.baidu.pcs.BaiduPCSClient;
import com.charmpeach.tsss.CourseManage;
import com.charmpeach.tsss.NewTopic;
import com.charmpeach.tsss.customer.LogInterface;
import com.charmpeach.tsss.customer.LogManager;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class MessageManger {

	private static MessageManger messageManger = null;

	private String sessionID = null;
	private DefaultHttpClient client = null;

	private Handler mbUiThreadHandler = null;
	
	public static MessageManger getInstance() {
		if (messageManger == null)
			messageManger = new MessageManger();
		return messageManger;
	}

	private MessageManger() {
		LogInterface li = new LogManager();

//		mbUiThreadHandler = new Handler();
		
		sessionID = li.login();
		if (sessionID == null)
			return;

		client = new DefaultHttpClient();
		HttpGet get = new HttpGet(
				"http://218.94.159.102/tss/en/home/postSignin.html?SIGlobalLogin="
						+ sessionID);
		try {
			client.execute(get);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String fetch(Context context) throws IOException
	{
		SharedPreferences pref = context.getSharedPreferences("MESSAGE",
				Context.MODE_APPEND);	
		
		String details = "";


		SortedSet<CourseInfoMessage> cims = new TreeSet<CourseInfoMessage>();

		String[] courseList = getFollowList(context).split(",");
		
		for(int i = 0; i < courseList.length; i++)
		{
			if(courseList[i] != null)
			{
				if(downloadFile(context,courseList[i] + ".txt"))
					cims.addAll(fetchCourseDetail(context,courseList[i]));
			}
		}

		for (CourseInfoMessage cim : cims)
			details = cim.toString() + details;
		Editor editor = pref.edit();
		editor.putString("message", details);
		editor.commit();
		return details;
	}
	
	public String getFollowCourseFromWeb()
	{
		String courseList = "";
		
		String url = "http://218.94.159.102/tss/en/home/mycourse.html";
		try
		{
			String htmlCode = getHtmlCode(url);

			String regex = "/tss/en/(c078[3-9]|c079[0-9]|c0800)/index.html";
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(htmlCode);

			while (matcher.find()) 
			{
				String courseID = matcher.group(1);
				courseList += courseID;
				courseList += ",";
			}
			
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return courseList;
	}


	public String getFollowList(Context context) {
		String courseList = null;
		SharedPreferences pre = context.getSharedPreferences("longinvalue",
				Activity.MODE_WORLD_WRITEABLE);
		String name = pre.getString("name", null);
		if ((courseList = pre.getString(name, null)) != null) {
			return courseList;
		} else {
			return null;
		}
	}
	
	private SortedSet<CourseInfoMessage> fetchCourseDetail(Context context,String courseID)	throws IOException {

		SortedSet<CourseInfoMessage> courseInfoMessages = new TreeSet<CourseInfoMessage>();

		String courseName = "";
		String instructor = "";
		
		File file = new File(context.getFilesDir().getPath()+"/", courseID + ".txt");
		
		InputStream in = new BufferedInputStream(new FileInputStream(file));
		InputStreamReader isr = new InputStreamReader(in, "GB2312");
		BufferedReader br = new BufferedReader(isr);
		
		// fetch course name
		courseName += br.readLine();
        System.out.println(courseName);
		// fetch teacher
		instructor += br.readLine();

		// fetch assignments		
		while(true)
		{
			
			String line = br.readLine();
			if(line.equals("Assignment End"))
				break;
			
			String assignmentNo = line;
			String content = br.readLine();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date time = null;
			try
			{
				time = sdf.parse(content);
			} catch (ParseException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			CourseTag tag = new CourseTag(TagType.ASSIGNMENT_TAG, courseID,
					assignmentNo);

			CourseInfoMessage cim = new CourseInfoMessage(courseName, instructor,
					"Deadline", content, time, tag);
			courseInfoMessages.add(cim);
			
			br.readLine();
		}

		// fetch announcement
		int announcementCount = 0;
		while(true)
		{
			String line = br.readLine();
			if(line.equals("Announcement End"))
				break;
			
			String timeStr = line;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date time = null;
			try
			{
				time = sdf.parse(timeStr);
			} catch (ParseException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			String content = br.readLine();
			announcementCount ++;
			
			CourseTag tag = new CourseTag(TagType.ANNOUNCEMENT_TAG, courseID,
					String.valueOf(announcementCount));

			CourseInfoMessage cim = new CourseInfoMessage(courseName, instructor,
					"Announcement", content, time, tag);

			courseInfoMessages.add(cim);
			
			br.readLine();
		}

		// fetch topic
		
		String line = br.readLine();
		while(true)
		{
			if(line.equals("All End"))
				break;
			
			String threadID = line;
			
			String timeStr = br.readLine();
			
			String content = br.readLine();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
			Date time = null;
			try
			{
				time = sdf.parse(timeStr);
			} catch (ParseException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			CourseTag tag = new CourseTag(TagType.FORUM_TAG, courseID, threadID);

			CourseInfoMessage cim = new CourseInfoMessage(courseName, instructor,
					"Topic", content, time, tag);

			courseInfoMessages.add(cim);
			
			line = br.readLine();
			
			while(true)
			{
				for (int j = 0; j < 4; j++)
				{
					br.readLine();
				}
				line = br.readLine();
				
				if(line.equals("Topic End"))
				{
					line = br.readLine();
					break;
				}
				if(line.equals("All End"))
					break;
			}
		}

		br.close();
		
		return courseInfoMessages;
	}

	private String getHtmlCode(String url) throws IOException {
		HttpGet request = new HttpGet(url);
		HttpResponse response = client.execute(request);

		BufferedReader br = new BufferedReader(new InputStreamReader(response
				.getEntity().getContent(), "GB2312"));

		String htmlCode = "";

		String line;
		while ((line = br.readLine()) != null)
			htmlCode += line;

		return htmlCode;
	}

	public String getAssignmentDetail(String courseID, String assignmentNo, Context context) throws IOException
	{
		String result = null;

		File file = new File(context.getFilesDir().getPath()+"/", courseID + ".txt");
		
		InputStream in = new BufferedInputStream(new FileInputStream(file));
		InputStreamReader isr = new InputStreamReader(in, "GB2312");
		BufferedReader br = new BufferedReader(isr);		
		
		// fetch course name
		br.readLine();

		// fetch teacher
		br.readLine();

		// fetch assignments		
		while(true)
		{
			
			String line = br.readLine();
			if(line.equals("Assignment End"))
				break;
			
			//String assignmentNo = line;
			String timeStr = br.readLine();			
			String content = br.readLine();
			
			if(line.equals(assignmentNo))
			{
				result = timeStr + "$" + content;
				System.out.println(result);
				break;
			}
		}
		
		br.close();
		
		return result;

	}
	
	public String getAnnouncementDetail(String courseID, String announcementNo, Context context) throws IOException
	{
		String result = null;

		File file = new File(context.getFilesDir().getPath()+"/", courseID + ".txt");
		
		InputStream in = new BufferedInputStream(new FileInputStream(file));
		InputStreamReader isr = new InputStreamReader(in, "GB2312");
		BufferedReader br = new BufferedReader(isr);
		
		int num = Integer.parseInt(announcementNo); 
		
		while(true)
		{
			String line = br.readLine();
			if(line.equals("Assignment End"))
				break;
		}
		
		for(int i = 1; i < num; i ++)
		{
			br.readLine();
			br.readLine();
			br.readLine();
		}
		
		String time = br.readLine();
		String title = br.readLine();
		String content = br.readLine();
		
		result=time+"$"+title+"$"+content;
		br.close();
		return result;
	}
	
	public String getTopicDetail(String courseID, String threadID, Context context) throws IOException
	{
		String result = null;

		File file = new File(context.getFilesDir().getPath()+"/", courseID + ".txt");
		
		InputStream in = new BufferedInputStream(new FileInputStream(file));
		InputStreamReader isr = new InputStreamReader(in, "GB2312");
		BufferedReader br = new BufferedReader(isr);
		
		while(true)
		{
			String line = br.readLine();
			if(line.equals("Announcement End"))
				break;
		}
		
		String line = br.readLine();
		while(true)
		{
			if(line.equals("All End"))
				break;
			
			String id = line;
			br.readLine();
			String title = br.readLine();
			
			
			line = br.readLine();
			
			if(!id.equals(threadID))
			{
				while(true)
				{
					for (int j = 0; j < 4; j++)
					{
						br.readLine();
					}
					line = br.readLine();
					
					if(line.equals("Topic End"))
					{
						line = br.readLine();
						break;
					}
				}
			}
			else 
			{
				result = title;
				while(true)
				{
					if(line.equals("Topic End"))
						break;
					//author
					result += "$" + line;
					
					//time
					String time = br.readLine();
					//quoting author
					String qAuthor = br.readLine() + " ";
					//quoting content
					String qContent = br.readLine() + " ";
					//content
					String content = br.readLine();
					
					result += "$" + time + "$" + qAuthor + "$" + qContent +  "$" + content;
					line = br.readLine();
				}
			}

		}
		
		br.close();
		return result;
	}
	
	private boolean downloadFile(Context context,String fileName)
	{
		final String file_name=fileName;
		final String mbOauth = "3.938f5bfe71085e17210f5f56493d5eba.2592000.1374424227.2668720875-1009550";
		final String mbRootPath = "/apps/tsss_android";

		BaiduPCSClient api = new BaiduPCSClient();
		api.setAccessToken(mbOauth);
		String source = mbRootPath + "/" + file_name;
		String target = context.getFilesDir().getPath()+"/"+file_name;
		final BaiduPCSActionInfo.PCSSimplefiedResponse ret = api.downloadFile(
				source, target);
		int count = 0;

		while(ret.errorCode != 0)
		{
			System.out.println(ret.errorCode);
			Log.e("sss", ret.message);
//			count++;
//			if(count > 100)
//				return false;
//			try
//			{
//				//Thread.sleep(100);
//			} catch (InterruptedException e)
//			{
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		}
		
		Log.e("download", "Download Success!");
		return true;
		
	}
	
	public static List<String>  filterMessage(List<String> messages,String type) {
		List<String> result=new ArrayList<String>();
		for(int i=0;i<messages.size();i++)
		{
			String details[]=messages.get(i).split(",");
			if(details[2].equals(type))
				result.add(messages.get(i));
		}
		return result;
	}
}
